package health_system.health_system.websocket.Test;

import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Simple WebSocket echo server for testing basic WebSocket functionality.
 */
@Slf4j
@Component
@ServerEndpoint(value = "/echo")
public class SimpleEchoServer {

    private static final Map<String, Session> sessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        String sessionId = session.getId();
        sessions.put(sessionId, session);
        log.info("Echo WebSocket opened - Session ID: {}, Total sessions: {}", sessionId, sessions.size());
        log.info("Session parameters: {}", session.getRequestParameterMap());
        log.info("URI: {}", session.getRequestURI());
        
        try {
            session.getBasicRemote().sendText("Connected to Echo WebSocket server!");
        } catch (IOException e) {
            log.error("Error sending welcome message", e);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("Received message from session {}: {}", session.getId(), message);
        
        try {
            session.getBasicRemote().sendText("Echo: " + message);
        } catch (IOException e) {
            log.error("Error sending echo response", e);
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        String sessionId = session.getId();
        sessions.remove(sessionId);
        log.info("Echo WebSocket closed - Session ID: {}, Reason: {}, Total sessions: {}", 
                sessionId, reason.getReasonPhrase(), sessions.size());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        String sessionId = session.getId();
        log.error("Echo WebSocket error - Session ID: {}, Error: {}", sessionId, error.getMessage(), error);
        sessions.remove(sessionId);
    }
} 